// const apiFetch    = form.dataset.api || form.action || "/api/douyin_fetch/";
// const apiDownload = form.dataset.downloadApi || "/api/douyin_download/";

function getCookie(name) {
  const m = document.cookie.match(new RegExp('(^|; )' + name + '=([^;]*)'));
  return m ? decodeURIComponent(m[2]) : null;
}
function getCsrfToken() {
  const el = document.querySelector('input[name="csrfmiddlewaretoken"]');
  return (el && el.value) || getCookie('csrftoken') || '';
}


// ===== 采集 · Ajax 渲染（卡片风版） =====
document.addEventListener("DOMContentLoaded", function () {
  const form = document.getElementById("dyForm");
  if (!form) return;

  const loadingBox = document.getElementById("dyLoading");
  const resultBox  = document.getElementById("dyResults");

  // 取 API：优先 data-api，其次 form.action，最后兜底
  const api = form.getAttribute("data-api") || form.getAttribute("action") || "/api/video_fetch/";

  // CSRF 辅助
  function getCookie(name) {
    const m = document.cookie.match(new RegExp('(^|; )' + name + '=([^;]*)'));
    return m ? decodeURIComponent(m[2]) : null;
  }
  function getCsrfToken() {
    const el = document.querySelector("input[name='csrfmiddlewaretoken']");
    return (el && el.value) || getCookie("csrftoken") || "";
  }

  // —— 统一的单条卡片渲染 —— //
  function renderItem(v) {
    // const placeholderUrl = "{% static 'picture/jinzhu.jpg' %}";
    const cover = v.cover_url
  ? `<img src="${v.cover_url}" alt="封面">`
  : `<img src="${window.DY_PLACEHOLDER}" alt="占位图">`;

    const link = v.url || v.url || "";

    return `
      <div class="dy-item">
        <div class="dy-row d-flex align-items-center gap-3">
          <div class="dy-thumb-wrap">
            ${cover}
          </div>
          <div class="flex-grow-1">
            <div class="dy-title">${v.title || "（无标题）"}</div>
            <div class="dy-meta">
              ${v.author || "未知"} · ${v.duration || "-"} · HDR:${v.hdr || "-"} · ${v.codec || "-"} 
            </div>
            ${v.page_url ? `<div class="text-muted small mt-1 text-truncate">原页：${v.page_url}</div>` : ""}
            <div class="dy-actions mt-2 d-flex gap-2 flex-wrap">
            
            
            <a class="btn btn-outline-primary" href="${'/' || "#"}" target="_blank" rel="noopener"
                 ${link ? "" : 'aria-disabled="true"'}>观看视频</a>
            
              <button type="button"
        class="btn btn-success download-btn video-download-btn"
        data-url="${link}" ${link ? "" : "disabled"}
        data-title="${(v.title || '').replace(/"/g, '&quot;')}"
        ${v.url ? '' : 'disabled'}>
              观看视频
              </button>


            </div>
          </div>
        </div>
      </div>
    `;
  }

  // —— 提交拦截：Ajax 请求 → 渲染 —— //
  // —— 提交拦截：Ajax 请求 → 渲染 —— //
form.addEventListener("submit", async function (e) {
  e.preventDefault();

  // 1) 判定是哪个按钮触发（单 / 主页）
  const submitter = e.submitter;
  const mode = submitter?.value || "single";

  // 2) 组装 FormData，附加 mode
  const fd = new FormData(form);
  fd.set("mode", mode);

  // 3) 选择接口地址：优先 data-api，其次 form.action，最后兜底
  const api =
    form.getAttribute("data-api") ||
    form.getAttribute("action") ||
    "/api/video_fetch/";

  // 4) UI：显示加载、清空旧结果
  if (loadingBox) loadingBox.classList.remove("d-none");
  if (resultBox) resultBox.innerHTML = "";

  try {
    // 5) 发请求（注意带上凭据 + CSRF）
    const resp = await fetch(api, {
      method: "POST",
      credentials: "same-origin",
      headers: { "X-CSRFToken": getCsrfToken() },
      body: fd,
    });

    if (!resp.ok) {
      const text = await resp.text();
      throw new Error(`HTTP ${resp.status} ${resp.statusText}\n${text.slice(0, 300)}`);
    }

    // 6) 解析 JSON
    let data;
    try {
      data = await resp.json();
    } catch {
      const text = await resp.text();
      throw new Error("返回的不是 JSON：\n" + text.slice(0, 300));
    }

    if (loadingBox) loadingBox.classList.add("d-none");

    // 7) 校验 & 渲染
    if (!(data && data.ok)) {
      resultBox.innerHTML = `<div class="alert alert-warning">接口异常：${JSON.stringify(data)}</div>`;
      return;
    }

    const list = Array.isArray(data.videos) ? data.videos : [];
    if (!list.length) {
      resultBox.innerHTML = `<div class="dy-empty">没有采集到相关视频，换个关键词试试~</div>`;
      return;
    }

    // 例如：resultBox.innerHTML = list.map(renderItem).join("");
    resultBox.innerHTML = list.map(renderItem).join("");

  } catch (err) {
    if (loadingBox) loadingBox.classList.add("d-none");
    console.error("[DY] 请求失败：", err);
    const safe = String(err).replace(/[<>&]/g, s => ({'<':'&lt;','>':'&gt;','&':'&amp;'}[s]));
    resultBox.innerHTML = `<div class="alert alert-danger">请求失败：<pre class="mb-0">${safe}</pre></div>`;
  }
});





});


// 清空按钮
document.addEventListener("DOMContentLoaded", function () {
  const input = document.querySelector("input[name='query']");
  const btnClear = document.getElementById("btnClear");

  if (btnClear) {
    btnClear.addEventListener("click", () => {
      input.value = "";
      input.focus();
    });
  }
});

// 播放 / 选集：点击按钮 -> 调 api_video_play -> 存到 sessionStorage -> 跳到 /select/
(function () {
  function getCsrfToken() {
    const m = document.cookie.match(/(?:^|; )csrftoken=([^;]+)/);
    return m ? decodeURIComponent(m[1]) : "";
  }
  function getPlayApi() {
    const hostForm = document.getElementById("dyForm");
    return (hostForm && (hostForm.getAttribute("data-play-api") || hostForm.getAttribute("data-download-api")))
           || "/api_video_play/";
  }

  document.addEventListener("click", async function (e) {
    const btn = e.target.closest(".video-download-btn"); // 你卡片上的绿色按钮
    if (!btn) return;

    const clueUrl = btn.dataset.url || "";               // 用于后端识别的视频线索（直链/分享页）
    const title   = (btn.dataset.title || "").trim();
    if (!clueUrl) return;

    // UI
    const oldHtml = btn.innerHTML, oldClass = btn.className;
    btn.disabled = true; btn.innerHTML = "加载选集…";

    try {
      const api = getPlayApi();
      const resp = await fetch(api, {
        method: "POST",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
          "X-CSRFToken": getCsrfToken()
        },
        body: new URLSearchParams({ u: clueUrl, title })
      });

      const data = await resp.json();
      if (!resp.ok || !data) throw new Error(`接口异常（${resp.status}）`);

      if (!data.ok) {
        throw new Error(data.error || "未获取到数据");
      }

      // —— 把返回的数据打包，存到 sessionStorage —— //
      const payload = {
        seriesId: data.series_id || data.id || "",
        title:    data.title || title || "",
        cover:    data.cover_url || "",
        author:   data.author || "",
        desc:     data.desc || "",
        episodes: data.episodes || [],
        // episodes: Array.isArray(data.episodes) ? data.episodes : [],
        // aTotal : data.aTotal || "",
        // 可选：把刚才的线索也带上，select页刷新兜底可能用得到
        clueUrl
      };
      sessionStorage.setItem("EP_SELECT_PAYLOAD", JSON.stringify(payload));

      // —— 跳转到选集页（带上 id，方便刷新兜底）—— //
      const q = payload.seriesId ? `?id=${encodeURIComponent(payload.seriesId)}` : "";
      window.location.href = `/select/${q}`;

    } catch (err) {
      console.error("[EP] 加载失败：", err);
      alert("选集加载失败：" + (err.message || err));
    } finally {
      setTimeout(() => { btn.innerHTML = oldHtml; btn.className = oldClass; btn.disabled = false; }, 500);
    }
  });
})();

